﻿using DevExpress.XtraEditors;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using MesProjectWinform.Entity.Request;
using MesProjectWinform.Helper;
using MesProjectWinform.Public;
using MesProjectWinform.Public.Common;
using MesProjectWinform.WareHouse.Entity;
using MesProjectWinform.用户控件;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.UI.WebControls;
using System.Windows.Forms;

namespace MesProjectWinform.WareHouse.Form.外部标签解析
{
    // 定义委托，用于传递规则字典数据
    public delegate void TagDataTransferHandler(List<KeyValuePair<string, string>> TagData, string Rules);

    public partial class Form_CheckTag : DevExpress.XtraEditors.XtraForm
    {
        // 声明事件，用于数据传递
        public event TagDataTransferHandler OnTagDataSelected;

        // 分页参数
        private int currentPage = 1;
        private int pageSize = 10;
        private int totalRecords = 0;
        private List<KeyValuePair<string, string>> listSelTagID = new List<KeyValuePair<string, string>>();
        int Index;
        // 添加公共属性返回选中的规则ID字典
        public List<KeyValuePair<string, string>> SelectedTagloyees
        {
            get { return listSelTagID; }
        }

        // 添加对话框结果标识
        public bool IsConfirmed { get; private set; } = false;

        public Form_CheckTag()
        {
            InitializeComponent();

        }

        /// <summary>
        /// 设置预选规则
        /// </summary>
        /// <param name="TagIds">规则ID字典</param>
        public void SetPreSelectedTagloyees(Dictionary<string, string> TagIds)
        {
            if (TagIds != null && TagIds.Count > 0)
            {
                // preSelectedTagIds = new Dictionary<string, string>(TagIds);
                listSelTagID = new List<KeyValuePair<string, string>>(TagIds.Select(x => new KeyValuePair<string, string>(x.Key, x.Value)));
                
                // 输出日志，方便调试
                System.Diagnostics.Debug.WriteLine($"预选规则数量: {listSelTagID.Count}");
                foreach (var item in listSelTagID)
                {
                    System.Diagnostics.Debug.WriteLine($"预选规则: {item.Key} - {item.Value}");
                }
            }
        }


        /// <summary>
        /// 加载数据
        /// </summary>
        private async void LoadData()
        {
            try
            {
                // 显示等待光标
                Cursor = Cursors.WaitCursor;
                
                // 调用API获取分页数据
                string action = $"WareHouse/BasicInfo/GetTagParseRules";
                await SelItemsIdTagAsync(action);
            }
            catch (Exception ex)
            {
                MessageBox.Show("加载分页数据时发生错误：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                // 恢复光标
                Cursor = Cursors.Default;
            }
        }

        /// <summary>
        /// 人员填充
        /// </summary>
        public async Task SelItemsIdTagAsync(string action )
        {
            try
            {
                string json = await HttpClientHelper.RequestUrl(RequestType.Get, action, null);// await APIClient.CallApiAsync(action, HttpMethod.GET);
                // 解析JSON响应
                ApiPaging<List<TagLableModel>> model = JsonConvert.DeserializeObject<ApiPaging<List<TagLableModel>>>(json);
                
                if (model == null || model.Data == null)
                {
                    MessageBox.Show("获取数据失败，返回结果为空", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                
                // 确保在UI线程上更新控件
                if (EmpGridView.InvokeRequired)
                {
                    EmpGridView.Invoke(new Action(() => UpdateUIWithData(model)));
                }
                else
                {
                    UpdateUIWithData(model);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("获取人员数据时发生错误：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        /// <summary>
        /// 使用获取的数据更新UI
        /// </summary>
        private void UpdateUIWithData(ApiPaging<List<TagLableModel>> model)
        {
            try
            {
                // 将数据转换为DataTable
                DataTable dt = DataConverHelper.ToDataTable(model.Data);
                
                // 更新数据网格
                EmpGridView.DataSource = dt;
                
                // 如果有预选数据，在数据加载完成后选中对应行
                if (listSelTagID.Count > 0)
                {
                    // 输出列名，帮助调试
                    System.Diagnostics.Debug.WriteLine("表格列信息:");
                    foreach (DataColumn col in dt.Columns)
                    {
                        System.Diagnostics.Debug.WriteLine($"列名: {col.ColumnName}, 类型: {col.DataType.Name}");
                    }
                    
                    // 在数据加载完成后调用方法来选中行
                    Application.Idle += new EventHandler(SelectRowsAfterLoad);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("更新UI数据时发生错误：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }


        private void CheckTagForm_Load(object sender, EventArgs e)
        {
            // 加载初始数据
            LoadData();
            
            // 加载完数据后，设置预选中的行
            if (listSelTagID.Count > 0)
            {
                // 更新标签显示已选择的数量
                labelControl1.Text = $"已选择 {listSelTagID.Count} 个项目。";
                
                // 更新规则文本框
                UpdateRulesTextBox();
            }
        }

        /// <summary>
        /// 更新规则文本框
        /// </summary>
        private void UpdateRulesTextBox()
        {
            try
            {
                if (listSelTagID == null || listSelTagID.Count == 0)
                {
                    txtRules.Text = string.Empty;
                    return;
                }

                StringBuilder sb = new StringBuilder();
                foreach (KeyValuePair<string, string> value in listSelTagID)
                {
                    if (sb.Length > 0)
                    {
                        sb.Append(",");
                    }
                    sb.Append(value.Value);
                }
                
                txtRules.Text = sb.ToString();
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"更新规则文本框时出错: {ex.Message}");
            }
        }

        /// <summary>
        /// 数据加载完成后选中行
        /// </summary>
        private void SelectRowsAfterLoad(object sender, EventArgs e)
        {
            try
            {
                // 只执行一次
                Application.Idle -= SelectRowsAfterLoad;
                
                System.Diagnostics.Debug.WriteLine("开始选中预选行...");

                // 遍历所有行，选中预选的行
                for (int i = 0; i < gridView1.RowCount; i++)
                {
                    DataRow row = gridView1.GetDataRow(i);
                    if (row != null)
                    {
                        // 获取当前行的ID
                        string rowId = string.Empty;
                        
                        // 尝试获取TagParseRulesId列的值
                        if (row.Table.Columns.Contains("TagParseRulesId"))
                        {
                            rowId = row["TagParseRulesId"].ToString();
                        }
                        // 如果没有TagParseRulesId列，尝试使用第一列
                        else if (row.ItemArray.Length > 0)
                        {
                            rowId = row.ItemArray[0].ToString();
                        }
                        
                        System.Diagnostics.Debug.WriteLine($"检查行 {i}, ID: {rowId}");
                        
                        // 如果ID在预选列表中，选中该行
                        if (!string.IsNullOrEmpty(rowId) && listSelTagID.Any(x => x.Key == rowId))
                        {
                            System.Diagnostics.Debug.WriteLine($"选中行 {i}, ID: {rowId}");
                            gridView1.SelectRow(i);
                        }
                    }
                }
                
                // 强制刷新视图
                gridView1.RefreshData();
                
                System.Diagnostics.Debug.WriteLine("预选行处理完成");
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"选中预选行时发生异常: {ex.Message}");
            }
        }

        private void gridView1_SelectionChanged(object sender, DevExpress.Data.SelectionChangedEventArgs e)
        {
            try
            {
                string Rules = string.Empty;
                int[] rownumber = this.gridView1.GetSelectedRows();//获取选中行号；
                int rowHandle = Index;

                var hitInfo = gridView1.CalcHitInfo(gridView1.GridControl.PointToClient(Control.MousePosition));

                // 判断是否点击的是列标题
                if (hitInfo.HitTest == GridHitTest.Column)
                {
                    foreach (var rowHandle1 in rownumber)
                    {
                        Boolean check = this.gridView1.IsRowSelected(rowHandle1);
                        DataRow row = this.gridView1.GetDataRow(rowHandle1);
                        if (row != null)
                        {
                            string tagId = row.ItemArray[0].ToString();
                            string tagName = row.ItemArray.Length > 1 ? row.ItemArray[1].ToString() : "";
                            
                            if (check)
                            {
                                if (!listSelTagID.Any(x => x.Key == tagId))
                                {
                                    listSelTagID.Add(new KeyValuePair<string, string>(tagId, tagName));
                                    //System.Diagnostics.Debug.WriteLine($"选中: {tagId} - {tagName}");
                                }
                            }
                            else
                            {
                                var itemToRemove = listSelTagID.FirstOrDefault(x => x.Key == tagId);
                                if (itemToRemove.Key != null)
                                {
                                     listSelTagID.Remove(itemToRemove);
                                    //System.Diagnostics.Debug.WriteLine($"取消选中: {tagId}");
                                }
                            }
                        }
                    }
                    if (rownumber.Length == 0)
                    {
                        listSelTagID.Clear();
                    }
                }
                else
                {
                    Boolean check = this.gridView1.IsRowSelected(rowHandle);
                    DataRow row = this.gridView1.GetDataRow(rowHandle);
                    if (row != null)
                    {
                        string tagId = row.ItemArray[0].ToString();
                        string tagName = row.ItemArray.Length > 1 ? row.ItemArray[1].ToString() : "";
                        
                        if (check)
                        {
                            if (!listSelTagID.Any(x => x.Key == tagId))
                            {
                                listSelTagID.Add(new KeyValuePair<string, string>(tagId, tagName));
                                System.Diagnostics.Debug.WriteLine($"选中: {tagId} - {tagName}");
                            }
                        }
                        else
                        {
                            var itemToRemove = listSelTagID.FirstOrDefault(x => x.Key == tagId);
                            if (itemToRemove.Key != null)
                            {
                                listSelTagID.Remove(itemToRemove);
                                System.Diagnostics.Debug.WriteLine($"取消选中: {tagId}");
                            }
                        }
                    }
                }
                
                // 更新规则文本
                UpdateRulesTextBox();

                labelControl1.Text = $"已选择 {listSelTagID.Count} 个项目。";
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"选择变更时发生异常: {ex.Message}");
            }
        }

        private void gridView1_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            Index = e.RowHandle;
        }

        /// <summary>
        /// 确认
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnAdd_Click(object sender, EventArgs e)
        {
            // 标记为已确认
            IsConfirmed = true;

            // 触发事件，传递选中的规则数据
            OnTagDataSelected?.Invoke(listSelTagID,txtRules.Text);

            // 关闭窗体
            this.DialogResult = System.Windows.Forms.DialogResult.OK;
            this.Close();
        }

        /// <summary>
        /// 关闭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnClose_Click(object sender, EventArgs e)
        {
            // 标记为取消
            IsConfirmed = false;
            this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this.Close();
        }
    }
}